package cn.shengchao.wecom.utils;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.shengchao.wecom.configure.WxCpConfiguration;
import cn.shengchao.wecom.configure.WxCpProperties;
import cn.shengchao.wecom.constants.WeComConstants;
import com.google.gson.JsonObject;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.util.json.GsonParser;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.user.WxCpDeptUserResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import top.continew.starter.core.exception.BaseException;


import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.User.USER_CONVERT_TO_OPENID;
import static me.chanjar.weixin.cp.constant.WxCpApiPathConsts.User.USER_LIST_ID;

/**
 * @program: examstarapi
 * @description: 通讯录同步工具类
 * @author: Xiong weiqiang
 * @create: 2025-04-10 11:48
 */
@Component
public class WeComTlxHelper {
    private static final String TXL_SECRET ="x8d1rx8yyMaLaDsr4fG8M26aatdPIpqllbtE9Pvguvs";
    private static final String GET_TOKEN_URL ="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=%s&corpsecret=%s";
    private static final Object SYNC_LOCK = new Object();
    @Autowired
    private WxCpProperties wxCpProperties;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    public Integer getAgentId(int index){
        Integer agentId = wxCpProperties.getAppConfigs().get(index).getAgentId();
        if (ObjectUtil.isNull(agentId)) {throw new BaseException("企微应用id没有配置");}
        return agentId;
    }

    public WxCpService getWxCpService(int index){
        return WxCpConfiguration.getCpService(getAgentId(index));
    }


    public synchronized String getToken(int index) throws WxErrorException {
        synchronized (SYNC_LOCK){
            if (stringRedisTemplate.hasKey(WeComConstants.TXL_TOKEN_PREFIX+index)){
                return stringRedisTemplate.opsForValue().get(WeComConstants.TXL_TOKEN_PREFIX+index);
            }else {
                String data = getWxCpService(0).get(String.format(GET_TOKEN_URL, wxCpProperties.getCorpId(),
                        TXL_SECRET), null);
                System.out.println("当前时间：" + System.currentTimeMillis());
                JSONObject txlTokenJson=new JSONObject(data);
                if (txlTokenJson.getInt("errcode")==0){
                    String token=txlTokenJson.getStr("access_token");
                    stringRedisTemplate.opsForValue().set(WeComConstants.TXL_TOKEN_PREFIX+index,token);
                    stringRedisTemplate.expire(WeComConstants.TXL_TOKEN_PREFIX+index,60*60*2-600,java.util.concurrent.TimeUnit.SECONDS);
                    return token;
                }
            }
            return null;
        }
    }
    public  String  getOpenIdForUserId(int index,String userId)throws WxErrorException {
        WxCpService wxCpService=getWxCpService(index);
        String token=getToken(index);
        if (token==null){
            throw new WxErrorException("企业通讯录token获取失败");
        }
        JSONObject jsonObject=new JSONObject();
        jsonObject.set("userid",userId);
        //调用接口，用户toOpenId
        String responseContent=wxCpService.postWithoutToken(wxCpService.getWxCpConfigStorage().getApiUrl(USER_CONVERT_TO_OPENID+"?access_token="+token),jsonObject.toString());
        JsonObject tmpJson = GsonParser.parse(responseContent);
        String openid=null;
        if (tmpJson.get("openid") != null) {
            openid= tmpJson.get("openid").getAsString();
        }
        return openid;
    }
    public WxCpDeptUserResult getWeComUserList(int index,String cursor,Integer limit)throws WxErrorException {
        WxCpService wxCpService=getWxCpService(index);
        String token=getToken(index);
        if (token==null){
            throw new WxErrorException("企业通讯录token获取失败");
        }
        JSONObject jsonObject=new JSONObject();
        if (ObjUtil.isNotNull(cursor)){
            jsonObject.set("cursor",cursor);
        }
        jsonObject.set("limit",limit);
        //调用接口，成员列表
        String responseContent=wxCpService.postWithoutToken(wxCpService.getWxCpConfigStorage().getApiUrl(USER_LIST_ID+"?access_token="+token),jsonObject.toString());
        WxCpDeptUserResult result=WxCpDeptUserResult.fromJson(responseContent);
        return result;
    }

    public WxCpUser getWeComUserInfo(int index,String userId)throws WxErrorException {
        WxCpService wxCpService=getWxCpService(index);
        String token=getToken(index);
        //https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID
        //不许url出现token
        String getParam="access_token="+token+"&userid="+userId;
        String responseContent1=wxCpService.get(wxCpService.getWxCpConfigStorage().getApiUrl("/cgi-bin/user/get"),getParam);
        return WxCpUser.fromJson(responseContent1);
    }
}